import {
    init,
    h
} from 'snabbdom'
//导入模块 
import style from 'snabbdom/modules/style'
import eventListeners from 'snabbdom/modules/eventlisteners'

//注册模块
let patch = init([
    style,
    eventListeners
])
let nextKey = 11
let oldVnode = null

var data = [{
        rank: 1,
        title: '《我和我的祖国》',
        elmHeight: 0
    },
    {
        rank: 2,
        title: '《我和我的家乡》',
        elmHeight: 0
    },
    {
        rank: 3,
        title: '《你好，李焕英》',
        elmHeight: 0
    },
    {
        rank: 4,
        title: '《盗墓笔记》',
        elmHeight: 0
    },
    {
        rank: 5,
        title: '《摔跤吧，爸爸》',
        elmHeight: 0
    },
    {
        rank: 6,
        title: '《天黑了》',
        elmHeight: 0
    },
    {
        rank: 7,
        title: '《红烧肉》',
        elmHeight: 0
    },
    {
        rank: 8,
        title: '《下雪了》',
        elmHeight: 0
    },
    {
        rank: 9,
        title: '《过年了》',
        elmHeight: 0
    },
    {
        rank: 10,
        title: '《放假了》',
        elmHeight: 0
    }
]
var dataCopy = Object.assign([], data)

//layout
function view(data) {
    let arr = []
    data.forEach(item => {
        //不设置key
        arr.push(h('li', [h('span', item.rank), h('span', item.title), h('button', {
            on: {
                click: [remove, item]
            }
        }, '删除')]))
    })
    let vnode = h('div', [h('button', {
        on: {
            click: add
        }
    }, '添加'), h('ul', arr)])
    return vnode
}

//渲染
function render() {
    let vnode = view(data)
    oldVnode = patch(oldVnode, vnode)
}

//添加
function add() {
    // 随机获取 originalData 中的一条数据
    var n = dataCopy[Math.floor(Math.random() * 10)]
    let newItem = {
        rank: nextKey++,
        title: n.title,
        elmHeight: 0
    }
    data.push(newItem)
    render()
}


//删除
function remove(item) {
    data.forEach((obj, index) => {
        if (item.rank === obj.rank) {
            data.splice(index, 1)
        }
    })
    render()

}

let app = document.querySelector('#app')
oldVnode = view(data)
patch(app, oldVnode)